/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.DRHclient.servlet;

import fr.DRHclient.models.*;
import fr.DRHclient.utils.AuthManager;
import fr.annuaireComp.clientUtils.CompetenceModel;
import fr.annuaireComp.clientUtils.ProfileModel;
import fr.annuaireComp.entities.Competence;
import fr.annuaireComp.entities.CompetencePersonnel;
import fr.annuaireComp.entities.Fonction;
import fr.annuaireComp.entities.Personnel;
import fr.annuaireComp.sessions.CompetencePersonnelManager;
import fr.annuaireComp.sessions.PersonnelManager;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author MiniK
 */
@WebServlet(name = "search", urlPatterns = {"/search"})
public class search extends HttpServlet {

    @EJB
    private PersonnelManager persMan;
    @EJB
    private CompetencePersonnelManager persCompMan;

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (!AuthManager.logUser(request, response)) {
            return;
        }
        Set<Competence> compSet = new HashSet<Competence>();
        List<CompetenceModel> compList = new ArrayList<CompetenceModel>();
        Competence c;
        for (CompetencePersonnel cp : persCompMan.listCompetencePersonnel()) {
            c = cp.getCompetence();
            if (compSet.add(c)) {
                compList.add(CompetenceModel.buildCompetenceModel(c, false));
            }
        }
        ProfileSearchModel searchData = new ProfileSearchModel();
        searchData.availableCompetencesForSearch = compList;
        request.setAttribute("searchdata", searchData);
        request.getRequestDispatcher("/WEB-INF/search.jsp").forward(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (!AuthManager.logUser(request, response)) {
            return;
        }
        try {
            HashMap<String, Object> searchCriteria = new HashMap<String, Object>();
            Set<Integer> compIdSearch = new HashSet<Integer>();
            String searchByParam;// = request.getParameter("searchby" + i);
            String valueParam;// = request.getParameter("value" + i);
            String paramName;

            for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
                paramName = (String) e.nextElement();
                if (paramName != null) {
                    if (paramName.startsWith("searchby")) {
                        searchByParam = request.getParameter(paramName).trim();
                        valueParam = request.getParameter("value" + paramName.replaceFirst("searchby", "")).trim();
                        if (!valueParam.isEmpty()) {
                            Object valueParamObj = formatCriteriaForSearch(searchByParam, valueParam);
                            searchCriteria.put(searchByParam, valueParamObj);
                        }
                    }
                    if (paramName.startsWith("compid")) {
                        try {
                            String cid = request.getParameter(paramName);
                            if (!cid.isEmpty()) {
                                Integer compId = Integer.parseInt(cid);

                                compIdSearch.add(compId);
                            }
                        } catch (Exception ex) {
                        }

                    }
                }
            }

            System.out.println("SUBMITTED PARAMS");
            for (Map.Entry<String, Object> item : searchCriteria.entrySet()) {
                System.out.println(item.getKey() + " : " + item.getValue());

            }
            System.out.println("----------------------------------");

            ProfileSearchResultsModel searchRezData = new ProfileSearchResultsModel();
            List<Personnel> persResults = new ArrayList<Personnel>();
            if (searchCriteria.size() > 0) {

                persResults.addAll(persMan.listPersonnelsBy(searchCriteria));
                //System.out.println("SEARCH RESULTS");
                if (compIdSearch.isEmpty()) {
                    for (Personnel p : persResults) {
                        searchRezData.profiles.add(ProfileModel.buildProfileModel(p));
                    }
                }
            }


            for (Integer id : compIdSearch) {
                if (persResults.isEmpty()) {
                    //RECHERCHE DE TOUS LES PERSONNEL QUI ONT CETTE COMPETENCE
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("competence", new Competence(id));
                    List<CompetencePersonnel> compPersList = persCompMan.listCompetenceBy(params);

                    for (CompetencePersonnel item : compPersList) {
                        searchRezData.profiles.add(ProfileModel.buildProfileModel(item.getPersonnel()));
                    }

                } else {
                    //REDUCE LA LIST DES PERSONNEL PAR LES COMPETENCES KI MATCHENT
                    //   boolean found = false;
                    for (Personnel p : persResults) {
                        for (CompetencePersonnel cp : p.getCompetencePersonnelList()) {
                            if (motherCompetenceSearch(cp.getCompetence(), id)) {
                                //filtrer avec les autres critères
                                boolean isgood = true;
                                String anneesXp = request.getParameter("anneesxp" + id);
                                String commentaires = request.getParameter("commentaire" + id);
                                if (!commentaires.isEmpty() && !commentaires.contains(cp.getCommentaire())) {
                                    isgood = false;
                                }
                                if (!anneesXp.isEmpty()) {
                                    try {
                                        if (Integer.parseInt(anneesXp) != cp.getAnneesXp()) {
                                            isgood = false;
                                        }
                                    } catch (Exception ex) {
                                    }
                                  
                                }
                                if(isgood){
                                      searchRezData.profiles.add(ProfileModel.buildProfileModel(p));
                                    break;
                                }
                            }

                        }

                    }
                }
            }



            request.setAttribute("searchresultsdata", searchRezData);
            request.getRequestDispatcher("/WEB-INF/searchresults.jsp").forward(request, response);
        } catch (Exception ex) {
            response.sendRedirect("search");//.forward(request, response);
        }

    }

    private boolean motherCompetenceSearch(Competence comp, Integer compId) {

        if (comp == null) {
            return false;
        }
        if (comp.getIdcompetence() == compId) {
            return true;
        }

        return motherCompetenceSearch(comp.getCompetenceMere(), compId);
    }

    private Object formatCriteriaForSearch(String name, String value) {
        if (name.equals("dateNaissance")) {
            try {
                return new SimpleDateFormat("dd/MM/yyyy").parse(value);
            } catch (ParseException ex) {
            }

        } else if (name.equals("sexe")) {
            if (value.toUpperCase().equals("F")) {
                return true;
            } else {
                return false;
            }
        } else if (name.equals("idfonction")) {
            try {
                return new Fonction(Integer.parseInt(value));
            } catch (Exception ex) {
            }
        }
        //TODO: voir si on check fonction

        return value;

    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
